<?php
namespace lib\JhWechat;

/**
 * 二维码
 * @Auth: JH <hu@lunaz.cn>
 * Class Qrcode
 * @package lib\JhWechat
 */
class Qrcode extends Base
{

    /**
     * @param array $options
     * @param string $access_token
     */
    function __construct( array $options = array(), $access_token = '' )
    {
        if ($access_token) {
            parent::$accessToken = $access_token;
        }
        if ($options) {
            parent::$config = $options;
        }
        parent::__construct();
    }

    /**
     * 临时二维码
     * @param int $scene_id
     * @param int $expire
     * @return array|false
     * <pre>
     * Array(
     *      [ticket] => gQEq8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmnvbS9xL3pFanp4b3psZ003NU1LVE1LMmJRAAIEGMNmVwMEgFEBAA==
     *      [expire_seconds] => 86400
     *      [url] => http://weixin.qq.com/q/zEjzxozlgM75MKTMK2bQ
     *      [scene] => 1
     * )
     * </pre>
     */
    function temporary( $scene_id, $expire = 86400 )
    {
        $scene_id = max( 1, min( (int)$scene_id, 4294967295 ) );
        $result = $this->create(
            array(
                'action_name' => 'QR_SCENE',
                'action_info' => array(
                    'scene' => array('scene_id' => $scene_id)
                ),
                'expire_seconds' => min( 2592000, $expire )
            )
        );
        if (isset( $result['ticket'] )) {
            $result['scene'] = $scene_id;
            return $result;
        }
        return false;
    }

    /**
     * 永久二维码
     * @param string|int $scene
     * @return array|false
     * <pre>
     * Array(
     *      [ticket] => gQEq8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmnvbS9xL3pFanp4b3psZ003NU1LVE1LMmJRAAIEGMNmVwMEgFEBAA==
     *      [url] => http://weixin.qq.com/q/zEjzxozlgM75MKTMK2bQ
     *      [scene] => $scene
     * )
     * </pre>
     */
    function lasting( $scene = '' )
    {
        $data = array(
            'action_name' => 'QR_LIMIT_SCENE',
            'action_info' => array(
                'scene' => array()
            )
        );
        if (is_int( $scene ) && $scene < 100000 && $scene > 0) {
            $data['action_info']['scene'] = array('scene_id' => $scene);
        } else {
            $data['action_info']['scene'] = array('scene_str' => "{$scene}");
            $data['action_name'] = 'QR_LIMIT_STR_SCENE';
        }
        $result = $this->create( $data );
        if (isset( $result['ticket'] )) {
            $result['scene'] = $scene;
            return $result;
        }
        return false;
    }

    private function create( array $data )
    {
        $result = $this->http(
            $this->makeUrl( '/qrcode/create', $this->getAccessToken() ),
            $data
        );
        return $result;
    }
}
